// components/Issue.js
import React, { useState, useEffect } from 'react';
import styles from '../css/issue.module.css';
import $ from 'jquery';
import leftImg from '../assets/left.png';
import hourse3 from '../assets/hourse3.png';
import qq1 from '../assets/upimage.png';
import qq2 from '../assets/camera.png';
import hua from '../assets/hua.png';
import wang from '../assets/wang.png';
import wu from '../assets/wu.png';
import { useNavigate } from 'react-router-dom';
import { uploadFile, addStrategy, addTravel, addQuestion } from '../api/issueApi'; // 引入封装好的接口
import { imgUrl } from '../config'; // 导入imgUrl
/**
 * 内容发布组件
 * 支持发布攻略、游记和问答等不同类型的内容
 */
const Issue = () => {
    // 状态管理
    const [state, setState] = useState(1);              // 当前内容类型（1:攻略 2:游记 3:问答 4:精选）
    const [stateing, setStateing] = useState(null);    // 精选内容的子类型
    const [userid, setUserid] = useState(sessionStorage.getItem("userid")); // 用户ID
    const [flie, setFlie] = useState(null);            // 第一张上传图片的URL
    const [flies, setFlies] = useState(null);          // 第二张上传图片的URL
    const [title, setTitle] = useState('');            // 内容标题
    const [content, setContent] = useState('');        // 内容正文
    const [charCount, setCharCount] = useState(0);     // 正文字符计数
    const [popupMessage, setPopupMessage] = useState(''); // 当前弹窗消息
    const [selectedImage, setSelectedImage] = useState(null); // 选中的景区图片
    const [showPopup, setShowPopup] = useState(false); // 控制弹窗显示状态
    const navigate = useNavigate();

    /**
     * 组件挂载时执行初始化
     */
    useEffect(() => {
        console.log(userid);
        strategys(); // 默认选择攻略类型
    }, []);

    // 内容类型选择方法
    const strategys = () => {
        setState(1);
        console.log(state);
    };

    const travels = () => {
        setState(2);
        console.log(state);
    };

    const questions = () => {
        setState(3);
        console.log(state);
    };

    // 精选内容子类型选择方法
    const best = () => {
        setState(4);
        setStateing(1);
        console.log(state, stateing);
    };

    const bestr = () => {
        setState(4);
        setStateing(2);
        console.log(state, stateing);
    };

    const besting = () => {
        setState(4);
        setStateing(3);
        console.log(state, stateing);
    };

    // 返回上一页
    const left = () => {
        window.history.back(-1);
    };

    /**
     * 处理第一张图片上传
     * @param {Event} e - 文件选择事件
     */
    const handleSingleImageUploadFirst = async (e) => {
        if (e.target.files.length > 0) {
            try {
                const file = e.target.files[0];
                const response = await uploadFile(file, userid);
                if (response.code === 1) {
                    e.target.value = ""; // 清空文件选择器
                    setFlie(response.data.url); // 更新图片URL
                } else {
                    console.log(response.data.msg);
                }
            } catch (error) {
                console.error('上传失败:', error);
            }
        } else {
            alert('请先选择文件！');
        }
    };

    /**
     * 处理第二张图片上传
     * @param {Event} e - 文件选择事件
     */
    const handleSingleImageUpload = async (e) => {
        if (e.target.files.length > 0) {
            try {
                const file = e.target.files[0];
                const response = await uploadFile(file, userid);
                if (response.data.code === 1) {
                    e.target.value = "";
                    setFlies(response.data.data.url);
                } else {
                    console.log(response.data.msg);
                }
            } catch (error) {
                console.error('上传失败:', error);
            }
        } else {
            alert('请先选择文件！');
        }
    };

    /**
     * 处理正文内容变化
     * @param {Event} e - 输入事件
     */
    const handleContentChange = (e) => {
        const text = e.target.value;
        setContent(text);
        setCharCount(text.length); // 更新字符计数
    };

    /**
     * 显示临时提示弹窗
     * @param {string} message - 提示消息内容
     */
    const showPopupFunction = (message) => {
        setPopupMessage(message); // 设置弹窗消息
        setShowPopup(true);
        setTimeout(() => {
            setShowPopup(false); // 2秒后自动关闭弹窗
        }, 2000);
    };

    /**
     * 处理内容提交
     */
    const handleSubmit = async () => {
        // 表单验证
        if (title === '') {
            showPopupFunction('请输入标题');
            return;
        }

        if (content === '') {
            showPopupFunction('请输入内容');
            return;
        }

        if (state === 3 && charCount < 10) {
            showPopupFunction('问答内容最少10个字');
            return;
        }

        if ((state === 1 || state === 2) && !flie && !flies) {
            showPopupFunction('请上传图片');
            return;
        }

        // 提交表单
        try {
            if (state === 1) {
                // 发布攻略
                const response = await addStrategy({
                    scenic_id: 3,        // 景区ID
                    bannar: flie,        // 封面图
                    introduce: content,  // 内容介绍
                    title: title,        // 标题
                    user_id: userid,     // 用户ID
                    img: flie,           // 图片
                });
                if (response.code === 1) {
                    showPopupFunction('发布成功！');
                    setTimeout(() => navigate("/game"), 2000); // 2秒后跳转到游戏页面
                }
            } else if (state === 2) {
                // 发布游记
                const response = await addTravel({
                    banner: flie,        // 封面图
                    user_id: userid,     // 用户ID
                    cover: flie,         // 封面图
                    content: content,    // 内容
                    title: title,        // 标题
                });
                if (response.data.code === 1) {
                    showPopupFunction('发布成功！');
                    setTimeout(() => navigate("/game"), 2000);
                }
            } else if (state === 3) {
                // 发布问答
                const response = await addQuestion({
                    user_id: userid,     // 用户ID
                    content: content,    // 内容
                    pid: 0,              // 父级ID（0表示顶级问题）
                });
                if (response.data.code === 1) {
                    showPopupFunction('发布成功！');
                    setTimeout(() => navigate("/game"), 2000);
                }
            }
        } catch (error) {
            console.error('发布失败:', error);
            showPopupFunction('发布失败，请重试！');
        }
    };

    /**
     * 处理景区图片选择
     * @param {string} imageName - 图片名称
     */
    const handleImageSelect = (imageName) => {
        setSelectedImage(imageName);
    };

    return (
        <div>
            {/* 通知消息区域 */}
            <div className={styles['hint-big']}>
                <div className={styles.hint}>
                    <div className={styles['hint-one']}>发布成功！</div>
                </div>
            </div>

            <div className={styles['hint-bigs']}>
                <div className={styles.hints}>
                    <div className={styles['hint-one']}>完善信息！</div>
                </div>
            </div>

            {/* 临时提示弹窗 */}
            {showPopup && (
                <div className={styles.popup}>
                    <div className={styles.popupContent}>
                        <p>{popupMessage}</p>
                    </div>
                </div>
            )}

            {/* 顶部导航栏 */}
            <div className={styles.top}>
                <div style={{ display: 'flex', alignItems: 'center', whiteSpace: 'nowrap', width: '50%', justifyContent: 'space-between' }}>
                    <div className={styles.left}>
                        <img style={{objectFit:'cover'}} src={leftImg} alt="" onClick={left} />
                        <div className={styles.line}></div>
                        <img style={{objectFit:'cover'}} id="hourse" src={hourse3} alt="" onClick={() => navigate("/home")} />
                    </div>
                </div>
                <p>发布攻略</p>
            </div>

            {/* 标题输入框 */}
            <div className={styles.title}>
                <div className={styles['title-one']}>
                    <input
                        type="text"
                        id="titles"
                        placeholder="好的标题能够吸引更多用户哦"
                        value={title}
                        onChange={(e) => setTitle(e.target.value)}
                    />
                </div>
            </div>
            
            {/* 图片上传区域 */}
            <div className={styles.image} style={{
                display: 'grid',
                gridTemplateColumns: '1fr 1fr',
                gap: '10px',
                alignItems: 'center',
                marginLeft:'-50px'
            }}>
                {/* 第一个上传组件 */}
                <div style={{
                    display: 'flex',
                    justifyContent: 'center',
                    marginTop: 0
                }}>
                    <div className={styles.borderImge} style={{ marginLeft: '20px', marginTop: '-4px' }}>
                        <img
                            src={flie ? `${imgUrl}${flie}` : qq1}
                            alt=""
                            id="imgbut"
                            onClick={() => document.getElementById('name').click()}
                            style={{ width: '75px', height: '75px',objectFit:'cover' }}
                        />
                    </div>
                    <input
                        type="file"
                        id="name"
                        style={{ display: 'none' }}
                        name="file"
                        onChange={handleSingleImageUploadFirst}
                    />
                </div>

                {/* 第二个上传组件 */}
                <div style={{
                    display: 'flex',
                    justifyContent: 'center',
                    marginTop: 0
                }}>
                    <div className={styles.borderImges} style={{ marginLeft: '-150px', marginTop: '-4px' }}>
                        <img
                            src={flies ? `${imgUrl}${flies}` : qq2}
                            alt=""
                            id="imgbuts"
                            onClick={() => document.getElementById('names').click()}
                            style={{ width: '75px', height: '75px',objectFit:'cover' }}
                        />
                    </div>
                    <input
                        type="file"
                        id="names"
                        style={{ display: 'none' }}
                        name="file"
                        onChange={handleSingleImageUpload}
                    />
                </div>
            </div>

            {/* 正文输入区域 */}
            <div className={styles['inputs-content']}>
                <textarea
                    id="area"
                    type="text"
                    placeholder="文字越多，越受欢迎"
                    value={content}
                    onChange={handleContentChange}
                ></textarea>
                <span>最少10个字，已写{charCount}字</span>
            </div>

            {/* 内容类型选择 */}
            <div className={styles.option}>
                <p>请选择类型:</p>&nbsp;&nbsp;&nbsp;
                <div className={styles.three}>
                    <input
                        type="radio"
                        onClick={strategys}
                        id="strategy"
                        value="显示"
                        name="1"
                        checked={state === 1}
                    />
                    <label htmlFor="strategy">攻略</label>
                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    <input
                        onChange={travels}
                        id="travel"
                        type="radio"
                        value="不显示"
                        name="1"
                        checked={state === 2}
                    />
                    <label htmlFor="travel">游记</label>
                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    <input
                        onChange={questions}
                        id="question"
                        type="radio"
                        value="不显示"
                        name="1"
                        checked={state === 3}
                    />
                    <label htmlFor="question">问答</label>
                </div>
            </div>

            {/* 景区选择区域 */}
            <div className={styles.option} style={{ marginTop: '20px' }}>
                <p>请选择景区:</p>
            </div>
            <div className={styles.additionalImages} style={{ display: 'flex', justifyContent: 'center', marginTop: '10px' }}>
                <div className={styles.imageContainer} style={{ position: 'relative', margin: '0 10px' }}>
                    <img
                        src={hua}
                        alt=""
                        style={{ width: '100px', height: '100px' }}
                        onClick={() => {
                            const radio = document.querySelector(`input[name="scenic"][value="hua"]`);
                            radio && radio.click();
                            handleImageSelect('hua');
                        }}
                    />
                    <input
                        type="radio"
                        checked={selectedImage === 'hua'}
                        onChange={() => handleImageSelect('hua')}
                        name="scenic"
                        value="hua"
                        style={{ position: 'absolute', top: '5px', right: '5px' }}
                    />
                </div>
                <div className={styles.imageContainer} style={{ position: 'relative', margin: '0 10px' }}>
                    <img
                        src={wang}
                        alt=""
                        style={{ width: '100px', height: '100px' }}
                        onClick={() => {
                            const radio = document.querySelector(`input[name="scenic"][value="wang"]`);
                            radio && radio.click();
                            handleImageSelect('wang');
                        }}
                    />
                    <input
                        type="radio"
                        checked={selectedImage === 'wang'}
                        onChange={() => handleImageSelect('wang')}
                        name="scenic"
                        value="wang"
                        style={{ position: 'absolute', top: '5px', right: '5px' }}
                    />
                </div>
                <div className={styles.imageContainer} style={{ position: 'relative', margin: '0 10px' }}>
                    <img
                        src={wu}
                        alt=""
                        style={{ width: '100px', height: '100px' }}
                        onClick={() => {
                            const radio = document.querySelector(`input[name="scenic"][value="wu"]`);
                            radio && radio.click();
                            handleImageSelect('wu');
                        }}
                    />
                    <input
                        type="radio"
                        checked={selectedImage === 'wu'}
                        onChange={() => handleImageSelect('wu')}
                        name="scenic"
                        value="wu"
                        style={{ position: 'absolute', top: '5px', right: '5px' }}
                    />
                </div>
            </div>

            {/* 发布按钮 */}
            <div className={styles.fn} onClick={handleSubmit}>
                发布
            </div>
        </div>
    );
};

export default Issue;    